/*
 * @Author: ZhangPeng irocky@email.cn
 * @Date: 2023-01-11 22:24:22
 * @Description:
 * @RoutePath:
 * Copyright (c) 2023 by ${git_name}, All Rights Reserved.
 */
import { defineStore } from 'pinia';
import { localRouteRecordRaw } from '@/router/routes/types';
import { localPermissionRoutes } from '@/router/routes';
import { filterLocalPermissonRoutes, handleAsyncRouter } from '@/hooks/route';
import { getRouters } from '@/api/user';
import useUserStore from '../user';

const useRouteStore = defineStore('route', {
  state: (): Record<string, localRouteRecordRaw[]> => ({
    routes: [],
    addRoutes: [],
    asyncRoutes: [],
    defaultRoutes: [],
    menuBarRouters: [],
  }),

  // getters: {
  //   userInfo(state: UserState): UserState {
  //     return { ...state };
  //   },
  // },

  actions: {
    // 接收请求路由，返回所有路由
    setRoutes(routes: localRouteRecordRaw[]) {
      this.asyncRoutes = routes;
      // this.routes = routes.concat(
      //   localRoutes as RouteRecordRaw[],
      // );
    },
    // 保存默认路由
    setDefaultRoutes(routes: localRouteRecordRaw[]) {
      this.defaultRoutes = routes;
    },
    // 保存请求路由
    setAsyncRoutes(routes: localRouteRecordRaw[]) {
      this.asyncRoutes = routes;
    },
    // 保存菜单路由
    setMenuRouters(routes: localRouteRecordRaw[]) {
      this.menuBarRouters = routes;
    },
    generateRoutes() {
      return new Promise<localRouteRecordRaw[]>((resolve) => {
        // 向后端请求路由数据
        getRouters().then((res) => {
          const userStore = useUserStore();
          // 检验本地权限路由
          const permissonRoutes = filterLocalPermissonRoutes(
            localPermissionRoutes,
            userStore.permissions,
            userStore.roles
          );
          const resData = JSON.parse(JSON.stringify(res.data));
          // 重复复制，传递会影响原始值
          // const menuData = JSON.parse(JSON.stringify(res.data));/
          const asyncRoutes = handleAsyncRouter(resData, true);
          this.setAsyncRoutes(asyncRoutes);
          this.setMenuRouters(asyncRoutes);
          // 合并本地权限路由及菜单路由
          resolve(permissonRoutes.concat(asyncRoutes));
        });
      });
    },
  },
});
export default useRouteStore;
